import { Modal } from "antd";
import { forwardRef, useContext, useImperativeHandle, useRef } from "react";
import { useGetState, useMemoizedFn, useSafeState, useUnmount } from "ahooks";
import * as rpcApis from "@/ui/utils/rpc";
import { LoadingOutlined } from "@ant-design/icons";
import events from "@/ui/events";
import { toast } from "sonner";
import { Avatar } from "@/ui/cpts/std/Avatar";
import { loadBrowserProfiles, syncBrowserSessions } from "@/ui/utils/rpc";
import { GlobalModel } from "@/ui/context";
import { BrowserProfile, BrowserSession } from "@common/models";
import { getValueOrDie } from "@common/utils";

interface Props {
  profile?: BrowserProfile;
  session?: BrowserSession;
  onSuccess?: (session: BrowserSession) => void;
}
export const OpenAccountDialog = forwardRef<
  { show: (visible: boolean) => void },
  Props
>(function OpenAccountDialog(props, ref) {
  const { profile, session, onSuccess } = props;
  const globalModel = useContext(GlobalModel);
  const [open, setOpen] = useSafeState(false);
  const [, setCreateResult, getCreateResult] = useGetState<Awaited<
    ReturnType<typeof rpcApis.createBrowserSession>
  > | null>();
  const [qrCodeImageUrl, setQrCodeImageUrl] = useSafeState("");
  const actionsOnUnmount = useRef<Array<() => void>>([]);
  const removeFromActionsOnUnmount = (action: () => void) => {
    actionsOnUnmount.current = actionsOnUnmount.current.filter(
      (r) => r !== action,
    );
  };

  const startSession = useMemoizedFn(async () => {
    if (!profile && session) {
      alert("程序错误，请重启程序");
      return;
    }

    const unhandlerB = events.Global.XHS.User.Check.on(
      async ({ user, sessionId }) => {
        if (!user) return;
        const createResult = getCreateResult();

        if (sessionId === createResult?.browserSessionId && user) {
          unhandlerB();
          removeFromActionsOnUnmount(unhandlerB);
          setOpen(false);
          const { sessions } = await syncBrowserSessions();
          const { profiles } = await loadBrowserProfiles();
          if (globalModel) {
            globalModel.sessions = sessions;
            globalModel.profiles = profiles;
          }

          const loginedSession = getValueOrDie(
            sessions.find((r) => r.id === sessionId),
          );
          if (onSuccess) {
            onSuccess(loginedSession);
          }

          toast(
            <div style={{ display: "flex", alignItems: "center" }}>
              <strong>登录成功：</strong>
              <div style={{ display: "inline-flex", alignItems: "center" }}>
                <Avatar
                  src={user.avatar}
                  size={"sm"}
                  style={{ display: "inline-block" }}
                />
                &nbsp;{user.nickname}
              </div>
            </div>,
          );
        } else {
          const tip = "登录失败";
          console.error(
            tip,
            "event:",
            "current:",
            createResult,
            new Error(tip),
          );
          toast(tip);
        }
      },
    );
    actionsOnUnmount.current.push(unhandlerB);

    const unhandlerA = events.Global.XHS.User.LoginQRCode.Show.on((params) => {
      const { url, sessionId } = params;
      const createResult = getCreateResult();
      if (createResult?.browserSessionId === sessionId) {
        unhandlerA();
        removeFromActionsOnUnmount(unhandlerA);
        setQrCodeImageUrl(url);
      } else {
        const tip = "session id 不匹配";
        console.error(tip, "event:", params, "current:", createResult);
        toast(tip);
      }
    });
    actionsOnUnmount.current.push(unhandlerA);

    const res = !profile
      ? await rpcApis.createBrowserSession()
      : await rpcApis.openBrowserSession(profile.id);
    setCreateResult(res);
  });

  const switchOpenStatus = useMemoizedFn(async (open: boolean) => {
    if (open) {
      setOpen(true);
      await startSession();
    } else {
      const createResult = getCreateResult();
      if (!createResult) {
        setOpen(true);
      } else {
        if (createResult) {
          await rpcApis.closeBrowserSession(createResult.browserSessionId);
        }
        setCreateResult(null);
        setQrCodeImageUrl("");
        setOpen(false);
      }
    }
  });

  useImperativeHandle(ref, () => ({
    show: switchOpenStatus,
  }));

  useUnmount(() => {
    actionsOnUnmount.current.forEach((action) => action());
  });

  return (
    <Modal
      maskClosable={false}
      open={open}
      title={<>{profile?.xhsUser ? "登录" : "新增"}账号</>}
      closable={!profile?.xhsUser && !!qrCodeImageUrl}
      destroyOnClose={true}
      footer={null}
      onCancel={() => switchOpenStatus(false)}
      keyboard={false}
    >
      <div>{!profile?.xhsUser && "扫码新增账号"}</div>

      <div
        style={{
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
          flexDirection: "column",
        }}
      >
        {qrCodeImageUrl ? (
          <img src={qrCodeImageUrl} alt={"qrcode"} />
        ) : (
          <>
            <LoadingOutlined style={{ fontSize: 60 }} />
            <div style={{ fontSize: 14, marginTop: 10 }}>
              {profile?.xhsUser ? "登录中" : "初始化中"}
            </div>
          </>
        )}
      </div>
    </Modal>
  );
});
